<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container" style="margin-bottom:20px">
      <span style="margin-left:10px">手机号码：</span>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输入用户手机号码" v-model="listQuery.mobile">
      </el-input>
      <!-- <span style="margin-left:10px">用户类型：</span>
      <el-select v-model="listQuery.userType" placeholder="请选择">
        <el-option v-for="item in userTypes" :key="item.code" :label="item.label" :value="item.code">
        </el-option>
      </el-select> -->
      <span style="margin-left:10px">所属学校：</span>
      <el-select v-model="listQuery.schoolId" clearable filterable remote reserve-keyword placeholder="请输入关键词" :remote-method="getSchoolOptions" :loading="isSchoolLoading">
        <el-option v-for="item in schoolsByTitleOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <span style="margin-left:10px">所属地区：</span>
      <el-cascader
           change-on-select clearable placeholder="全部" expand-trigger="click"
          :options="areas"
          v-model="listQuery.areaIds"
        ></el-cascader>
      <span style="margin-left:10px">用户昵称：</span>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="请输入用户昵称" v-model="listQuery.nickname">
      </el-input>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <br>
      <el-button class="filter-item" style="margin-left: 10px;margin-top: 5px;" type="primary" icon="el-icon-upload2" @click="handleExportFile" size="small">导出</el-button>
      <el-button class="filter-item" style="margin-left: 10px;margin-top: 5px;" type="primary" icon="el-icon-upload2" @click="batchImportExcel" size="small">批量导入</el-button>
    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="数据加载中，请稍后" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="用户ID" min-width="50">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="110" align="center" label="昵称" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.nickName}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="120" align="center" label="手机号" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.mobile}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="120" align="center" label="所属地区" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.areaName}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="120" align="center" label="所属学校" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.title}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="100" align="center" label="班级" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.gradeClassName}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="120" align="center" label="注册时间" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.createTime | dateformat('YYYY-MM-DD HH:mm')}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="60" align="center" label="是否禁言" prop="title" show-overflow-tooltip>
        <template slot-scope="{row}">
          {{row.forbidden == 1 ? '是' : '否'}}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="150">
        <template slot-scope="{row}">
          <el-button size="small" @click="handleModifyStatus(row)">编辑</el-button>
          <el-button size="small" @click="handleToggleAllowSpeak(row)">{{ row.forbidden | transForbidden(false)}}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNo" :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog title="编辑用户" :visible.sync="dialogFormVisible" center :before-close="handleClose" >
      <el-form :model="temp" :rules="rules" ref="ruleForm" label-position="right" label-width="100px" style='width: 70%; margin-left:50px;'>
       
        <el-form-item label="用户昵称" label-width="80px" prop="nickName">
          <span>{{temp.nickName ? temp.nickName : '--'}}</span>
        </el-form-item>

        <el-form-item label="用户姓名" label-width="80px" prop="name">
          <span>{{temp.name ? temp.name : '--'}}</span>
        </el-form-item>

        <el-form-item label="所属地区" label-width="80px">
            <el-cascader change-on-select  clearable placeholder="请选择所属地区" expand-trigger="click" :options="areaCascadeOptionss" v-model="areaOption" @change="getSchools($event)" />
            <span style="color:red;">{{msgArea}}</span>
            <span>{{temp.areaName ? temp.areaName : '--'}}</span>
        </el-form-item>

        <el-form-item label="学校" label-width="80px" prop="schoolId">
          <el-select v-model="schoolOption" v-show="isShow==1" clearable >
              <el-option v-for="item in schools" :key="item.id" :label="item.title" :value="item.id"></el-option>
          </el-select>
          <span>{{temp.schoolName ? temp.schoolName : '--'}}</span>
        </el-form-item>

        <el-form-item label="年级" label-width="80px" prop="gradeId">
          <el-select v-model="gradeId" placeholder="请选择" clearable >
              <el-option v-for="grade in gradeList" :key="grade.id" :label="grade.gradeName" :value="grade.id"></el-option>
          </el-select>
          <span>{{temp.gradeId == 1 ? '高一' : temp.gradeId == 2 ? '高二' : temp.gradeId == 3 ? '高三' : '--'}}</span>
        </el-form-item>

        <el-form-item label="班级" label-width="80px" prop="className">
          <el-select v-model="className" placeholder="请选择" clearable >
            <el-option
                v-for="item in classList"
                :key="item"
                :label="item+'班'"
                :value="item+'班'">
            </el-option>
          </el-select>
          <span>{{temp.className ? temp.className : '--'}}</span>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="updateForm">确 定</el-button>
      </div>
    </el-dialog>

    <Import-Excel :dialog="batchDialog" @cancel="batchDialog = false" @reloadList="reloadList"></Import-Excel>

  </div>
</template>

<script>
import { getList, getAreaList, getSchoolsById, update, getId, getUserType, userForbidden, exportUserInfoExcel, showUserInfo, getHighSchool, updateUser } from '@/api/user'
import { getAreaCascadeSupply, getArea } from '@/api/academy'
import ImportExcel from './components/importExcel'
import { mapGetters, mapActions } from 'vuex'
import { exportFile } from '@/utils'

const transForbidden = (status, boolean = true) => {
  if (boolean) return status == 1 ? '禁言' : '解封'
  return status == 1 ? '解封' : '禁言'
}
export default {
  name: 'list',
  components: { ImportExcel },
  watch: {
    areaOption(e){
      if(e.length != 3){
        this.isShow = 0
        this.msgArea = '所属地区必须选择到区级'
      }else{
        this.isShow = 1
        this.msgArea = ''
      }
    }
  },
  data() {
    return {
      isShow: 0,
      schools: [],
      areas: [],
      gradeId:null,
      className:null,
      schoolOption: null,
      areaOption: [],
      version: [],
      userTypes: [],
      inputVisible: false,
      inputValue: '',
      dateformat: '',
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        areaId: null,
        areaIds: [],
        pageNo: 1,
        pageSize: 10,
        mobile: '',
        // userType: '',
        schoolId: '',
        title: '',
        nickname:null
      },
      classList: [],
      gradeList: [
        { id:1, gradeName:'高一' },
        { id:2, gradeName:'高二' },
        { id:3, gradeName:'高三' }
      ],
      temp: {
        userId:null,
        name:null,
        nickName:null,
        intro:null,
        schoolId: null,
        schoolName:null,
        areaId:null,
        areaName:null,
        labels: [],
        gradeId:null,
        className:null
      },
      dialogFormVisible: false,
      rules: {
        areaId: [{ required: true, message: '请选择所属地区', trigger: 'change' }],
        schoolId: [{ required: true, message: '请选择所属学校', trigger: 'change' }]
        // userType: [{ required: true, message: '请选择用户类型', trigger: 'change' }]
      },
      tableKey: 0,
      showAllDel: false,
      multipleSelection: [],
      pageBoolean: {
        delColor: 'primary',
        delText: '批量删除'
      },
      params:{
        areaId:null
      },
      schoolOptions: [],
      isSchoolLoading: false,
      batchDialog: false,
      msgArea:'',
      areaCascadeOptionss:[]
    }
  },
  mounted() {
    this.getList()
    this.getAreaCascadeSupply()
    this.fetchAreaData()
    this.getClassNames()
  },
  filters: {
    statusFilter(status) {
      const statusMap = { '1': '学生', '2': '家长' }
      return statusMap[status]
    },
    transForbidden
    
  },
  computed: {
    ...mapGetters(['schoolsByTitleOptions'])
  },
  methods: {
    // 获得班级数据
    getClassNames(){
      let i = 1
      const list = []
      for(i; i < 100; i++){
        list.push(i)
      }
      this.classList = list
    },
    // 映射 Actions
    ...mapActions(['GetSchoolsByTitleOptions']),

    getSchoolOptions(title) {
      if (title) this.GetSchoolsByTitleOptions(title)
    },
    handleClose() {
      this.$confirm('数据未保存，确认关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogFormVisible = false
      }).catch(() => {})
    },
    // 获得完整的区域级联
    getAreaCascadeSupply(){
      getAreaCascadeSupply().then(res => {
        if(res.code == 0){
          this.areaCascadeOptionss = res.data
        }
      }).catch(err => {})
    },
    // 获得学校数据
    getSchools(val){
      if(val.length == 3){
        this.temp.areaId = val[val.length - 1]
        this.params.areaId = this.temp.areaId
        if(this.params != null && this.params != '' && this.params != undefined){
          getHighSchool(this.params).then(res => {
            if(res.code == 0){
              this.schools = res.data
            }
          }).catch(err => {})
        }
      }else{
        this.msgArea = '所属地区必须选择到区级'
      }
    },

    // 导出列表
    handleExportFile() {
      const { listQuery, listQuery:{ areaIds } } = this
      if(areaIds.length == 0){
        listQuery['areaId'] = null
      }
      console.log(listQuery)
      exportUserInfoExcel(listQuery)
        .then(({ data }) => {
          if (data) exportFile(data)
        })
    },

    // excel用户
    batchImportExcel() {
      this.batchDialog = true
    },

    reloadList() {
      setTimeout(() => {
        this.getList()
      }, 500)
    },

    // 禁言解封
    handleToggleAllowSpeak({ forbidden, id }) {
      userForbidden({
        action: forbidden == 1 ? 0 : 1,
        userId: id
      })
        .then(() => {
          this.$message({
            message: `${transForbidden(forbidden, false)}成功！`,
            type: 'success'
          })
          this.getList()
        })
    },

    // handleChange(areaIds) {
    //   const areaId = areaIds[areaIds.length - 1]
    //   this.fetchSchoolData(areaId, 2)
    // },
    // fetchSchoolData(id, type) {
    //   getSchoolsById(id).then(response => {
    //     this.schools = response.data
    //     if (type == 1) {
    //       this.dialogFormVisible = true
    //     } else {
    //       if (response.data.length == 0) {
    //         this.schoolOption = ''
    //       } else {
    //         this.schoolOption = response.data[0]['schoolId']
    //       }
    //     }
    //   })
    // },
    // fetchUserType() {
    //   getUserType().then(response => {
    //     const types = response.data
    //     types[0]['label'] = '全部'
    //     types[0]['code'] = ''
    //     this.userTypes = types
    //   })
    // },
    fetchAreaData() {
      getAreaList().then(response => {
        this.areas = response.data
      })
    },
    getList() {
      this.listLoading = true
      const params = this.listQuery
      getList(params).then(response => {
        const { code, data: { total, list = [] } } = response
        if (code == 0) {
          this.total = total
          this.list = list
          this.listLoading = false
        }
      })
    },
    handleFilter() {
      const { listQuery:{ areaIds } } = this
      if(areaIds.length > 0){
        this.listQuery.areaId = areaIds[areaIds.length - 1]
      }else{
        this.listQuery.areaId = null
      }
      this.listQuery.pageNo = 1

      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    // 编辑
    handleModifyStatus(row) {
      showUserInfo(row.id).then(res => {
        const { data } = res
        this.temp = data
        this.temp.userId = row.id
        this.dialogFormVisible = true
      })
      // getId(row.id).then(response => {
      //   let { data } = response
      //   this.temp = data
      //   let areaIds = data['areaIds'];
      //   let aIds=[]
      //   if (areaIds.length != 0) {
      //     areaIds.split(',').map(e => {
      //       if(e != 'null'){
      //         e = parseInt(e)
      //         aIds.push(e)
      //       }
      //     })
      //   }
      //   this.areaOption = aIds;
      //   //获取区域所属学校
      //   this.schoolOption = data['schoolId']
      //   if(!data.hasOwnProperty('areaId')){
      //     data['areaId'] = aIds[aIds.length-1];
      //   }
      // this.fetchSchoolData(data['areaId'], 1)

      // })
    },
    updateForm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const { temp, schoolOption, areaOption, gradeId, className } = this
          const params = {}
          params['userId'] = temp['userId']
          params['schoolId'] = schoolOption
          params['areaId'] = areaOption[areaOption.length - 1]
          params['gradeId'] = gradeId
          params['className'] = className
          if(this.areaOption.length != 0 && this.schoolOption == null){
            this.$message({
              title: '失败',
              message: '学校与所属地区，要么全填，要么全不填',
              type: 'error',
              duration: 2000
            })
            return
          }
          updateUser(params).then(response => {
            const { code, message } = response
            if (code == 0) {
              this.areaOption = []
              this.schoolOption = null
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }else{
              this.$message({
                title: '失败',
                message: message,
                type: 'error',
                duration: 2000
              })
            }
          }).catch(err => {})
            .finally(() => this.gradeId = null,
              this.className = null
            )
        }
      })
    },
    handleDelete(idx, row) {
    },
    handleRefresh() {
      this.list = null
      this.total = null
      this.listQuery.pageNo = 1
      this.getList()
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.icon-ctx {
  width: 160px;
  height: 80px;
  overflow: hidden;
  margin: 0 auto;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.app-container {
  padding: 20px;
}
.pagination-container {
  margin-top: 30px;
}
</style>